package com.sftz.modules.minapp.educationSign.service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.sftz.assets.entities.EducationAuditEntity;
import com.sftz.assets.entities.EducationRegistrationEntity;
import com.sftz.assets.entities.InstitutionEntity;
import com.sftz.assets.entities.RegistrationInformationEntity;
import com.sftz.assets.entities.SeriesCoursesEntity;
import com.sftz.assets.entities.UserCoursesltEntity;
import com.sftz.assets.entities.UserProductEntity;
import com.sftz.assets.enums.CheckStatusEnum;
import com.sftz.assets.enums.EducationEnum;
import com.sftz.assets.enums.HouseTypeEnum;
import com.sftz.assets.enums.IdentTypeEnum;
import com.sftz.assets.enums.InstitutionTypeEnum;
import com.sftz.assets.enums.OldEmaterEnum;
import com.sftz.assets.enums.PoliticsTypeEnum;
import com.sftz.assets.enums.RegisTypeEnum;
import com.sftz.assets.enums.RegisterStateEnum;
import com.sftz.assets.enums.SexEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.modules.minapp.educationSign.dto.EduEnumInfDto;
import com.sftz.modules.minapp.educationSign.dto.EducationSignDto;
import com.sftz.modules.minapp.educationSign.dto.MajorInfoDto;
import com.sftz.modules.minapp.educationSign.form.RegistrationInformationUpdateForm;
import com.sftz.modules.minapp.educationSign.form.SignInfoAddForm;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.BeanUtil;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.util.DbSqlUtil;
import com.uxuexi.core.redis.RedisDao;
import com.uxuexi.core.web.base.service.BaseService;

/**
 * 个人中心   学历注册
 * @author 郝振斌
 *
 * 2018年12月17日
 */
@IocBean
public class EducationSignViewService extends BaseService<RegistrationInformationEntity> {
	private static final Log log = Logs.get();

	@Inject
	private RedisDao redisDao;

	/**
	 * 添加学历注册相关信息
	 * @param addForm
	 * @return
	 */
	@Aop("txDb")
	public Object addSignInfo(SignInfoAddForm addForm) {
		Integer userId =  RedissionUserCache.getUserId(addForm.getToken());
		Integer majorId = addForm.getMajorId();
		EducationRegistrationEntity fetchDto = dbDao.fetch(EducationRegistrationEntity.class,
				Cnd.where("majorId", "=", majorId).and("userId", "=", userId));
		if (!Util.isEmpty(fetchDto)) {//校验此专业是否注册过
			return 0;
		} else {
			EducationRegistrationEntity edu = new EducationRegistrationEntity();
			RegistrationInformationEntity info = new RegistrationInformationEntity();
			edu.setUserId(userId);
			edu.setRegisterState(EnumUtil.getKeyInt(RegisterStateEnum.PENDINGAPPROVAL));
			edu.setMajorId(addForm.getMajorId());
			//学历注册表添加相关数据
			Integer registrationId = dbDao.insert(edu).getId();
			addForm.setRegistrationId(registrationId);
			//学历信息表添加相关数据
			BeanUtil.copyProperties(addForm, info);
			RegistrationInformationEntity registrationInformationEntity = dbDao.insert(info);
			//学历审核表添加相关数据
			EducationAuditEntity Aud = new EducationAuditEntity();
			Aud.setEducationAuditpreviousState(EnumUtil.getKeyInt(RegisterStateEnum.PENDINGAPPROVAL));
			Aud.setEducationAuditResult(EnumUtil.getKeyInt(RegisterStateEnum.PENDINGAPPROVAL));
			Aud.setRegistrationId(registrationId);
			EducationAuditEntity educationAuditEntity = dbDao.insert(Aud);
			if (!Util.isEmpty(registrationInformationEntity) && !Util.isEmpty(educationAuditEntity)) {
				return 1;//注册成功返回值
			} else {
				return 2;//注册失败返回值
			}
		}
	}

	/**
	 * 获取注册机构相关信息
	 * @return
	 */
	public Object getEducationEnumMap() {
		Map<String, Object> valueMap = new HashMap<String, Object>();
		Map<String, String> enum2 = EnumUtil.enum2(EducationEnum.class);
		Map<String, String> identType = EnumUtil.enum2(IdentTypeEnum.class);
		Map<String, String> politicsType = EnumUtil.enum2(PoliticsTypeEnum.class);
		Map<String, String> houseType = EnumUtil.enum2(HouseTypeEnum.class);
		Map<String, String> regisType = EnumUtil.enum2(RegisTypeEnum.class);
		Map<String, String> oldEmater = EnumUtil.enum2(OldEmaterEnum.class);
		Map<String, String> yesOrNo = EnumUtil.enum2(YesOrNoEnum.class);
		Map<String, String> sex = EnumUtil.enum2(SexEnum.class);
		valueMap.put("EducationEnumMap", enum2);
		valueMap.put("identType", identType);
		valueMap.put("politicsType", politicsType);
		valueMap.put("houseType", houseType);
		valueMap.put("regisType", regisType);
		valueMap.put("oldEmater", oldEmater);
		valueMap.put("yesOrNo", yesOrNo);
		valueMap.put("sex", sex);
		valueMap.put(
				"insititution",
				dbDao.query(
						InstitutionEntity.class,
						Cnd.where("institutionType", "=", InstitutionTypeEnum.EDUCATIONINSTITUTIONS.intKey()).and(
								"insititutionState", "=", CheckStatusEnum.ENABLE.intKey()), null));
		return valueMap;
	}

	/**
	 * 获取审核结果页面信息
	 * @param collegeId 
	 * @param id
	 * @return
	 */
	public Object checkResult(long educationInfoId) {
		Map<String, Object> obj = new HashMap<String, Object>();
		//获取学历注册信息表id
		//Integer educationInfoId = getEducationInfoId(id);
		//获取相关学历注册信息
		RegistrationInformationEntity infoD = dbDao.fetch(RegistrationInformationEntity.class, Cnd.where("registrationId", "=", educationInfoId));
		obj.put("signInfo",infoD);
		//翻译枚举
		Integer sex = infoD.getSex();
		Integer identType = infoD.getIdentType();
		Integer politicsType = infoD.getPoliticsType();
		Integer isJob = infoD.getIsJob();
		Integer regisType = infoD.getRegisType();
		Integer oldEmater = infoD.getOldEmater();
		
		String sexS = EnumUtil.getValue(SexEnum.class, sex);
		String identTypeS = EnumUtil.getValue(IdentTypeEnum.class, identType);
		String politicsTypeS = EnumUtil.getValue(PoliticsTypeEnum.class, politicsType);
		String isJobS = EnumUtil.getValue(YesOrNoEnum.class, isJob);
		String regisTypeS = EnumUtil.getValue(RegisTypeEnum.class, regisType);
		String oldEmaterS = EnumUtil.getValue(OldEmaterEnum.class, oldEmater);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		
		String birthday = sdf.format(infoD.getBirthday());
		String graduationDate = sdf.format(infoD.getGraduationDate());
		EduEnumInfDto dto = new EduEnumInfDto();
		dto.setSex(sexS);
		dto.setIdentType(identTypeS);
		dto.setPoliticsType(politicsTypeS);
		dto.setIsJob(isJobS);
		dto.setRegisType(regisTypeS);
		dto.setOldEmater(oldEmaterS);
		dto.setBirthday(birthday);
		dto.setGraduationDate(graduationDate);
		obj.put("enumDto",dto);
		
		//获取相关审核意见信息
		obj.put("auditInfo", dbDao.fetch(EducationAuditEntity.class, Cnd.where("registrationId", "=", educationInfoId)));
		//获取相关注册专业信息
		Sql majorInfoSql = Sqls.create(sqlManager.get("education_majorInfo"));
		majorInfoSql.setParam("signId", educationInfoId);
		MajorInfoDto majorInfo = DbSqlUtil.fetchEntity(dbDao, MajorInfoDto.class, majorInfoSql);
		obj.put("majorInfo", majorInfo);
		EducationRegistrationEntity registration = dbDao.fetch(EducationRegistrationEntity.class,
				Cnd.where("id", "=", educationInfoId));
		obj.put("userRegis", registration);
		if (!Util.isEmpty(registration)) {
			//判断当前学生选课情况-未选（直接跳到专业选课页面）已选课直接跳转学习相关页面
			UserProductEntity fetch = dbDao.fetch(UserProductEntity.class,
					Cnd.where("productId", "=", registration.getMajorId()).and("userId", "=", registration.getUserId())
							.and("orderType", "=", 1));
			obj.put("userPro", fetch);
			UserCoursesltEntity userCourseslt = dbDao.fetch(UserCoursesltEntity.class, Cnd.where("seriesId", "=", registration.getMajorId()).
					and("userId", "=", registration.getUserId()));
			obj.put("userCourseslt", userCourseslt);
		}
		return obj;
	}

	/**
	 * 获取学生对应的注册信息id
	 * @param id
	 * @return
	 */
	public Integer getEducationInfoId(long id) {
		//根据用户id获取注册表id
		EducationRegistrationEntity entity = dbDao.fetch(EducationRegistrationEntity.class,
				Cnd.where("userId", "=", id));
		return entity.getId();
	}

	/**
	   * 审核不通过修改学历注册信息
	   * @param id
	 * @param collegeId 
	   * @return
	   */
	public Object fetchValue(long id) {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("educationMap", getEducationEnumMap());
		RegistrationInformationEntity infoD = dbDao.fetch(RegistrationInformationEntity.class, Cnd.where("registrationId", "=", id));
		obj.put("info", infoD);
		
		//翻译枚举
		Integer sex = infoD.getSex();
		Integer identType = infoD.getIdentType();
		Integer politicsType = infoD.getPoliticsType();
		Integer isJob = infoD.getIsJob();
		Integer regisType = infoD.getRegisType();
		Integer oldEmater = infoD.getOldEmater();
		
		String sexS = EnumUtil.getValue(SexEnum.class, sex);
		String identTypeS = EnumUtil.getValue(IdentTypeEnum.class, identType);
		String politicsTypeS = EnumUtil.getValue(PoliticsTypeEnum.class, politicsType);
		String isJobS = EnumUtil.getValue(YesOrNoEnum.class, isJob);
		String regisTypeS = EnumUtil.getValue(RegisTypeEnum.class, regisType);
		String oldEmaterS = EnumUtil.getValue(OldEmaterEnum.class, oldEmater);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		
		String birthday = sdf.format(infoD.getBirthday());
		String graduationDate = sdf.format(infoD.getGraduationDate());
		EduEnumInfDto dto = new EduEnumInfDto();
		dto.setSex(sexS);
		dto.setIdentType(identTypeS);
		dto.setPoliticsType(politicsTypeS);
		dto.setIsJob(isJobS);
		dto.setRegisType(regisTypeS);
		dto.setOldEmater(oldEmaterS);
		dto.setBirthday(birthday);
		dto.setGraduationDate(graduationDate);
		obj.put("enumDto",dto);
		
		//获取注册专业id
		Sql sql = Sqls.create(sqlManager.get("education_majorId"));
		sql.setParam("id", id);
		Integer majorId = DbSqlUtil.fetchInt(dbDao, sql);

		Sql majorTypeSql = Sqls.create(sqlManager.get("education_majorType"));
		majorTypeSql.setParam("majorId", majorId);
		//机构选中索引
		Integer insIndex = 0;
		Integer insititutionId = DbSqlUtil.fetchInt(dbDao, majorTypeSql);
		List<InstitutionEntity> insList = dbDao.query(InstitutionEntity.class,Cnd.where("institutionType", "=", InstitutionTypeEnum.EDUCATIONINSTITUTIONS.intKey()).and(
						"insititutionState", "=", CheckStatusEnum.ENABLE.intKey()), null);
		for (int i = 0; i < insList.size(); i++) {
			InstitutionEntity s = insList.get(i);
			Integer sId = s.getId();
			if(sId == insititutionId){
				insIndex = i;
				break;
			}
		}
		obj.put("insIndex", insIndex);
		obj.put("insititutionId", insititutionId);

		//专业选中索引
		Integer majorIndex = 0;
		List<SeriesCoursesEntity> majorList = (List<SeriesCoursesEntity>) selectMajor(insititutionId);
		for (int i = 0; i < majorList.size(); i++) {
			SeriesCoursesEntity s = majorList.get(i);
			Integer sId = s.getId();
			if(sId == majorId){
				majorIndex = i;
				break;
			}
		}
		obj.put("majorId", majorId);
		obj.put("majorIndex", majorIndex);
		obj.put("majorList", majorList);
		obj.put("majorName", majorList.get(majorIndex).getName());
		
		return obj;
	}

	//筛选出机构对应的专业
	public Object selectMajor(long institutionId) {
		return dbDao.query(
				SeriesCoursesEntity.class,
				Cnd.where("insititutionId", "=", institutionId).and("status", "=", YesOrNoEnum.YES.key())
						.and("isDelete", "=", YesOrNoEnum.NO.intKey()), null);
	}

	//审核注册信息修改保存
	public Object updateSave(RegistrationInformationUpdateForm updateForm) {
		Integer userId =  RedissionUserCache.getUserId(updateForm.getToken());
		Integer majorId = updateForm.getMajorId();
		Integer majorOldId = updateForm.getMajorOldId();
		EducationRegistrationEntity fetchDto = dbDao.fetch(EducationRegistrationEntity.class,
				Cnd.where("majorId", "=", majorId).and("userId", "=", userId));
		/*if (!Util.isEmpty(fetchDto) && fetchDto.getRegisterState().equals(RegisterStateEnum.PENDINGAPPROVAL.intKey())) {
			return 2;
		}*/
		if (!majorOldId.equals(majorId) && !Util.isEmpty(fetchDto)) {//校验此专业是否注册过
			return 0;//校验注册专业是否重复
		} else {
			dbDao.update(EducationAuditEntity.class,
					Chain.make("educationAuditResult", EnumUtil.getKeyInt(RegisterStateEnum.PENDINGAPPROVAL)),
					Cnd.where("registrationId", "=", updateForm.getRegistrationId()));
			dbDao.update(
					EducationRegistrationEntity.class,
					Chain.make("majorId", updateForm.getMajorId()).add("registerState",
							EnumUtil.getKeyInt(RegisterStateEnum.PENDINGAPPROVAL)),
					Cnd.where("id", "=", updateForm.getRegistrationId()));
			update(updateForm);
			return 1;//注册专业修改成功
		}
	}

	//注册专业列表显示
	public Object list(String token) {
		Integer userId = RedissionUserCache.getUserId(token);
		Sql sql = Sqls.create(sqlManager.get("education_infoList"));

		sql.setParam("userId", userId);
		/*sql.setParam("start", (pager.getPageNumber() - 1) * pager.getPageSize());
		sql.setParam("pageSize", pager.getPageSize());*/

		List<EducationSignDto> list = DbSqlUtil.query(dbDao, EducationSignDto.class, sql);

		EducationSignDto signDto = new EducationSignDto();

		Integer registerState = null;

		for (int i = 0; i < list.size(); i++) {
			signDto = list.get(i);
			registerState = signDto.getRegisterState();
			RegisterStateEnum registerStateEnum = EnumUtil.get(RegisterStateEnum.class, registerState);
			switch (registerStateEnum) {
			case PENDINGAPPROVAL:
				signDto.setSignState(RegisterStateEnum.PENDINGAPPROVAL.value());
				break;
			case AUTHENTICATIONFAILURE:
				signDto.setSignState(RegisterStateEnum.AUTHENTICATIONFAILURE.value());
				break;
			case AUTHENTICATED:
				signDto.setSignState(RegisterStateEnum.AUTHENTICATED.value());
				break;
			case FIRSTTRIALSUS:
				signDto.setSignState(RegisterStateEnum.FINALTRIALWAIT.value());
				break;
			case FINALTRIALWAIT:
				signDto.setSignState(RegisterStateEnum.FINALTRIALWAIT.value());
				break;
			case FINALTRIALBEAT:
				signDto.setSignState(RegisterStateEnum.FINALTRIALBEAT.value());
				break;
			default:
				break;
			}
			
			UserProductEntity fetch = dbDao.fetch(
					UserProductEntity.class,
					Cnd.where("productId", "=", signDto.getMajorId()).and("userId", "=", userId)
							.and("orderType", "=", 1));
			if (Util.isEmpty(fetch)) {
				signDto.setOrderStatus("未支付");
			} else {
				signDto.setOrderStatus("已支付");
			}
		}

		if (list.size() == 0) {
			return null;
		} else {
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("list", list);
			temp.put("listCnt", fetchEduCnt(userId));
			return temp;
		}
	}

	/**
	 * 查询注册学历的总条数
	 * @param nickName
	 * @return
	 */
	public Object fetchEduCnt(Integer userId) {

		Sql sql = Sqls.create(sqlManager.get("education_infoListCount"));

		sql.setParam("userId", userId);

		return DbSqlUtil.fetchInt(dbDao, sql);

	}

}